<template>
<div class="com-container">
	<div class="com-chart" ref="hotRef" id="hotRef"></div>
  <span class="iconfont left" :style="comStyle" @click="left">&#xe6ef;</span>
  <span class="iconfont right" :style="comStyle" @click="right">&#xe6ed;</span>
  <span class="cat-name" :style="comStyle">
			{{ state.catName }}
	</span>
</div>
</template>
<script lang='ts' setup>
import { ref, reactive, onMounted, onUnmounted, computed, watch } from 'vue';
import socketService from '../api/socket_sever'
import * as echarts from 'echarts'
import '../../public/theme/chalk'
import {gethotproduct} from '../api/api'
import { useStore } from 'vuex';
import { getThemeValue } from '@/utils/theme_utils';
const store = useStore()
  const hotRef = ref()
  const comStyle = computed( () => {
				return {
					fontSize: state.titleFontSize + 'px',
					color: getThemeValue(store.state.theme).titleColor
				}
			})
	const state = reactive<{
    // myChart: echarts.ECharts | null,
    data: API.hotproduct[]
    currentPage: number
    totalPage: number
    setinter: number
    currentindex: number
    catName:string
    titleFontSize: number
	}>({
    // myChart: null,
    data: [],// 服务器返回数据
    currentPage: 1,// 第几多少页
    totalPage: 0, // 一共多少页
    setinter: 0,
    currentindex: 0,
    catName: '',
    titleFontSize: 0
	})
  let myChart: echarts.ECharts | null = null
	onMounted(async() => {
      await initexs()
      screenAdapter()
      window.addEventListener('resize',screenAdapter )
	})
  onUnmounted(() => {
    clearInterval(state.setinter)
    window.removeEventListener('resize', screenAdapter)
    socketService.Instance.unRegisterCallBack('hotproduct')
  })
  // 初始化exs
  const initexs = async() => {
    var chartDom = document.getElementById('hotRef');
    myChart = echarts.init(chartDom as HTMLElement, store.state.theme)
    const initoption = {
      title: {
        text: '▎商家销售统计',
        left: 20,
        top: 20
      },
      legend: {
        top: '10%',
        right: '10%',
        icon: 'circle'
      },
      grid: {
        // top: '10%',
        containLabel: true
      },
      series: [
        {
          type: 'pie'
        }
      ]
    }
    initoption && (myChart as  echarts.ECharts).setOption(initoption);
    socketService.Instance.registerCallBack('hotproduct', getData)
    try {
      await gethotproduct()
    } catch (error) {
      console.log(error);
    }
  }
    // 获取数据
  const getData = (data:API.hotproduct[]) => {
    state.data = data
    updataChar()
  }

    // 更新图表
  const updataChar = () => {
    state.catName = state.data[state.currentindex].name
    const showdata = state.data[state.currentindex].children.map(item => {
      return {
        name: item.name,
        value: item.value,
        children: item.children
      }
    })
    const legentdata = state.data[state.currentindex].children.map(item => {
      return {
        name: item.name
      }
    }) 
    const dataoption = {
      legend: {
        data: legentdata
      },
      series: [
        {
          data: showdata
        }
      ],
      tooltip: {
        show: true,
				formatter: (arg: any) => {
          let totar = 0
          let retStar = ''
          arg.data.children.map( (item:any) => {
            totar += item.value
          })
          arg.data.children.map( (item:any) => {
            retStar += `${item.name}:${((item.value / totar * 100) as any).toFixed(2) + '%' + '<br/>'}`
          })
          return retStar
        }
			}
    }
    dataoption && (myChart as  echarts.ECharts).setOption(dataoption);
  }
  const screenAdapter = () => {
    state.titleFontSize = hotRef.value.offsetWidth / 100 * 3.6;
    // console.log(titleFontSize);
    const Adapteroption = {
      title: {
        textStyle: {
          fontSize: state.titleFontSize
        }
      },
			tooltip: {
				axisPointer: {
					lineStyle: {
						width: state.titleFontSize
					}
				}
			},
      series:[ 
        {
          radius: '60%'
        }],
      legend: {
        itemWidth: state.titleFontSize / 1.5,
        itemHeight: state.titleFontSize / 1.5,
        itemGap:  state.titleFontSize,
        textStyle: {
          fontSize: state.titleFontSize / 3
        }
      },
    }
    Adapteroption && (myChart as  echarts.ECharts).setOption(Adapteroption);
    (myChart as  echarts.ECharts).resize()
  }
  const right = () => {
    if (state.currentindex === 2) {
      state.currentindex = 0
      updataChar()
    } else {
      state.currentindex++
      updataChar()
    }
  }
  const left = () => {
    if (state.currentindex === 0) {
      state.currentindex = state.data.length - 1
      updataChar()
    } else {
      state.currentindex--
      updataChar()
    }
  }
    defineExpose({
    screenAdapter
  })
  watch ( () => store.state.theme, async() => {
    // console.log('qweqwe');
    (myChart as echarts.ECharts).dispose();
    await initexs()
    screenAdapter()
    updataChar()
  }, {
    // immediate: true, // 是否初始化立即执行一次, 默认是false
    deep: true // 是否是深度监视, 默认是false
  })
</script>
<style lang='less' scoped>
.right{
  position: absolute;
  right: 5%;
  top: 50%;
  transform: translateY(-50%);
  width: 50px;
  cursor: pointer;
  color: #fff;
  font-size: 50px;
}
.left{
  position: absolute;
  left: 5%;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  color: #fff;
  font-size: 50px;
}

.cat-name {
	position: absolute;
	left: 85%;
	bottom: 20px;
	color: white;
  color: #fff;
}
</style>